﻿using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using DataScripter.Scripting.InputSources;

namespace DataScripter.Database.SqlServer
{
    public class SqlServerDb : Db
    {
        public SqlServerDb(string instance, string database) : base(instance, database)
        {
        }

        public SqlServerDb(string connectionString)
        {
            Instance = ExtractInstance(connectionString);
            Database = ExtractDatabase(connectionString);
        }

        public SqlServerDb(ISqlServerInputSource inputSource) : this(inputSource.ConnectionString)
        {
        }

        private static string ExtractDatabase(string connectionString)
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);
            return builder.InitialCatalog;
        }

        private static string ExtractInstance(string connectionString)
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);
            return builder.DataSource;
        }

        protected override IDbConnection GetOpenConnection()
        {
            string connectionString = GetConnectionstring();
            SqlConnection connection = new SqlConnection(connectionString);
            connection.Open();
            return connection;
        }

        protected override DbDataAdapter CreateDataAdapter(IDbConnection connection, string query)
        {
            return new SqlDataAdapter(query, (SqlConnection) connection);
        }

        private string GetConnectionstring()
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder
            {
                Pooling = false,
                DataSource = Instance,
                InitialCatalog = Database,
                WorkstationID = Environment.MachineName,
                IntegratedSecurity = true
            };

            return builder.ConnectionString;
        }
    }
}
